import React, { useState, useEffect } from 'react';
import { Modal, View, Text, TouchableOpacity, StyleSheet, ScrollView } from 'react-native';
import { Touchable } from 'react-native-toast-message/lib/src/components/Touchable';
import { WebView } from 'react-native-webview';
import { useReactive } from 'ahooks';

interface IDeteTimePickerProps {
  visible: boolean;
  title?: string; // 可选标题
  currentDate?: { date: string[]; time: string[] };
  onConfirm: (date: { date: string[]; time: string[] }) => void;
  onCancel: () => void;
  closeOnClickOverlay?: boolean; // 是否在点击遮罩层后关闭
}

interface IState {
  uri: string;
  result: { names: string; values: Array<string | number> };
}
const DeteTimePicker: React.FC<IDeteTimePickerProps> = ({ visible, closeOnClickOverlay, currentDate, onCancel, onConfirm, title = '选择' }) => {
  const state = useReactive<IState>({
    uri: 'https://kics.kanglailab.com/dateTimePicker',
    result: { names: '', values: [] },
  });

  useEffect(() => {
    if (visible) state.uri = `https://kics.kanglailab.com/dateTimePicker?_title=${title}&_currentDate=${JSON.stringify(currentDate || '')}`;
  }, [visible]);

  /**
   * 处理来自 WebView 的消息
   * @param event
   */
  const handleWebViewMessage = async (event: any) => {
    const message = JSON.parse(event.nativeEvent.data);
    if (message.onConfirm) {
      onConfirm(message.onConfirm);
    }
    if (message.onCancel) {
      onCancel();
    }
  };

  return (
    <Modal visible={visible} transparent animationType="fade">
      <View style={styles.container}>
        <Touchable
          style={styles.touchArea}
          onPress={() => {
            closeOnClickOverlay ? onCancel() : undefined;
          }}
        >
          <View></View>
        </Touchable>
        <View style={styles.container}>
          <View style={styles.pickerContainer}>
            <View style={styles.pickerContent}>
              <WebView style={{ width: '100%', height: '100%' }} source={{ uri: state.uri }} onMessage={handleWebViewMessage} />
            </View>
          </View>
        </View>
      </View>
    </Modal>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'flex-end', backgroundColor: 'rgba(0,0,0,0.2)' },
  touchArea: { flex: 1, backgroundColor: 'rgba(0,0,0,0.2)' },
  pickerContent: { position: 'relative', height: 350, paddingTop: 5, justifyContent: 'center', paddingHorizontal: 16 },
  pickerContainer: { backgroundColor: '#fff', borderTopLeftRadius: 20, borderTopRightRadius: 20, paddingBottom: 20 },
});

export default DeteTimePicker;
